/**
 * 营养成分计算工具函数
 */

import type { Food, FoodIntake, NutritionSummary, OtherNutrient } from '@/types'

/**
 * 根据食物和摄入量计算营养成分
 * @param food 食物信息（每100g的营养数据）
 * @param amountG 摄入量（克）
 * @returns 计算后的营养成分
 */
export function calculateNutrition(food: Food, amountG: number): NutritionSummary {
  const ratio = amountG / 100 // 计算比例

  return {
    energy_kcal: Math.round((food.energy_kcal || 0) * ratio * 10) / 10,
    protein_g: Math.round((food.protein_g || 0) * ratio * 10) / 10,
    fat_g: Math.round((food.fat_g || 0) * ratio * 10) / 10,
    carb_g: Math.round((food.carb_g || 0) * ratio * 10) / 10,
    fiber_g: Math.round((food.fiber_g || 0) * ratio * 10) / 10,
    sodium_mg: Math.round((food.sodium_mg || 0) * ratio * 10) / 10,
    calcium_mg: Math.round((food.calcium_mg || 0) * ratio * 10) / 10,
    iron_mg: Math.round((food.iron_mg || 0) * ratio * 10) / 10,
    vitamin_c_mg: Math.round((food.vitamin_c_mg || 0) * ratio * 10) / 10
  }
}

/**
 * 计算其他营养素（other_nutrients）
 * @param food 食物信息
 * @param amountG 摄入量（克）
 * @returns 计算后的其他营养素数组
 */
export function calculateOtherNutrients(food: Food, amountG: number): OtherNutrient[] {
  if (!food.other_nutrients || food.other_nutrients.length === 0) {
    return []
  }

  const ratio = amountG / 100 // 计算比例

  return food.other_nutrients.map(nutrient => ({
    ...nutrient,
    amount: nutrient.amount ? Math.round(nutrient.amount * ratio * 10) / 10 : undefined
  }))
}

/**
 * 合并多个食物的其他营养素
 * @param foodIntakes 食物摄入记录数组
 * @returns 合并后的其他营养素数组（按nutrient_id分组求和）
 */
export function mergeOtherNutrients(foodIntakes: FoodIntake[]): OtherNutrient[] {
  const nutrientMap = new Map<number | undefined, OtherNutrient>()

  foodIntakes.forEach(intake => {
    const otherNutrients = calculateOtherNutrients(intake.food, intake.amount_g)

    otherNutrients.forEach(nutrient => {
      const key = nutrient.nutrient_id
      const existing = nutrientMap.get(key)

      if (existing) {
        // 累加相同营养素的量
        existing.amount = (existing.amount || 0) + (nutrient.amount || 0)
        existing.amount = Math.round(existing.amount * 10) / 10
        // 如果任一标记为rich，则结果为rich
        existing.rich = existing.rich || nutrient.rich
      } else {
        nutrientMap.set(key, { ...nutrient })
      }
    })
  })

  return Array.from(nutrientMap.values())
}

/**
 * 计算多个食物摄入的总营养成分
 * @param foodIntakes 食物摄入记录数组
 * @returns 总营养成分
 */
export function calculateTotalNutrition(foodIntakes: FoodIntake[]): NutritionSummary {
  const total: NutritionSummary = {
    energy_kcal: 0,
    protein_g: 0,
    fat_g: 0,
    carb_g: 0,
    fiber_g: 0,
    sodium_mg: 0,
    calcium_mg: 0,
    iron_mg: 0,
    vitamin_c_mg: 0
  }

  foodIntakes.forEach(intake => {
    const nutrition = calculateNutrition(intake.food, intake.amount_g)

    total.energy_kcal += nutrition.energy_kcal
    total.protein_g += nutrition.protein_g
    total.fat_g += nutrition.fat_g
    total.carb_g += nutrition.carb_g
    total.fiber_g += nutrition.fiber_g
    total.sodium_mg += nutrition.sodium_mg
    total.calcium_mg += nutrition.calcium_mg
    total.iron_mg += nutrition.iron_mg
    total.vitamin_c_mg += nutrition.vitamin_c_mg
  })

  // 四舍五入到一位小数
  Object.keys(total).forEach(key => {
    total[key as keyof NutritionSummary] = Math.round(total[key as keyof NutritionSummary] * 10) / 10
  })

  return total
}

/**
 * 格式化营养成分显示
 * @param nutrition 营养成分数据
 * @returns 格式化后的显示对象
 */
export function formatNutritionDisplay(nutrition: NutritionSummary) {
  return {
    '能量': `${nutrition.energy_kcal} 千卡`,
    '蛋白质': `${nutrition.protein_g} g`,
    '脂肪': `${nutrition.fat_g} g`,
    '碳水化合物': `${nutrition.carb_g} g`,
    '膳食纤维': `${nutrition.fiber_g} g`,
    '钠': `${nutrition.sodium_mg} mg`,
    '钙': `${nutrition.calcium_mg} mg`,
    '铁': `${nutrition.iron_mg} mg`,
    '维生素C': `${nutrition.vitamin_c_mg} mg`
  }
}

/**
 * 获取营养成分的颜色标识（用于图表显示）
 */
export const nutritionColors = {
  energy_kcal: '#FF6B6B',
  protein_g: '#4ECDC4',
  fat_g: '#45B7D1',
  carb_g: '#96CEB4',
  fiber_g: '#FFEAA7',
  sodium_mg: '#DDA0DD',
  calcium_mg: '#98D8C8',
  iron_mg: '#F7DC6F',
  vitamin_c_mg: '#BB8FCE'
}

/**
 * 获取营养成分的推荐摄入量（成人每日推荐量）
 */
export const dailyRecommendedIntake = {
  energy_kcal: 2000, // 千卡
  protein_g: 60,     // 克
  fat_g: 67,         // 克
  carb_g: 300,       // 克
  fiber_g: 25,       // 克
  sodium_mg: 2300,   // 毫克
  calcium_mg: 1000,  // 毫克
  iron_mg: 18,       // 毫克
  vitamin_c_mg: 90   // 毫克
}

/**
 * 计算营养成分占推荐摄入量的百分比
 * @param nutrition 营养成分数据
 * @returns 百分比对象
 */
export function calculateNutritionPercentage(nutrition: NutritionSummary) {
  const percentages: Record<string, number> = {}
  
  Object.keys(nutrition).forEach(key => {
    const nutrientKey = key as keyof NutritionSummary
    const value = nutrition[nutrientKey]
    const recommended = dailyRecommendedIntake[nutrientKey]
    
    if (recommended > 0) {
      percentages[key] = Math.round((value / recommended) * 100)
    }
  })
  
  return percentages
}

/**
 * 验证食物摄入量是否合理
 * @param amountG 摄入量（克）
 * @returns 验证结果
 */
export function validateFoodIntakeAmount(amountG: number): { valid: boolean; message?: string } {
  if (amountG <= 0) {
    return { valid: false, message: '摄入量必须大于0' }
  }
  
  if (amountG > 2000) {
    return { valid: false, message: '单次摄入量不能超过2000克' }
  }
  
  return { valid: true }
}

/**
 * 生成营养成分报告
 * @param foodIntakes 食物摄入记录
 * @param date 日期
 * @returns 营养报告
 */
export function generateNutritionReport(foodIntakes: FoodIntake[], date: string) {
  const totalNutrition = calculateTotalNutrition(foodIntakes)
  const percentages = calculateNutritionPercentage(totalNutrition)
  const formattedDisplay = formatNutritionDisplay(totalNutrition)
  const totalOtherNutrients = mergeOtherNutrients(foodIntakes)

  return {
    date,
    totalFoods: foodIntakes.length,
    totalWeight: foodIntakes.reduce((sum, intake) => sum + intake.amount_g, 0),
    nutrition: totalNutrition,
    percentages,
    formattedDisplay,
    otherNutrients: totalOtherNutrients, // 添加其他营养素汇总
    foods: foodIntakes.map(intake => ({
      name: intake.food.name_zh,
      amount: intake.amount_g,
      nutrition: calculateNutrition(intake.food, intake.amount_g),
      otherNutrients: calculateOtherNutrients(intake.food, intake.amount_g) // 添加每个食物的其他营养素
    }))
  }
}
